package com.baizhi.ems_thymeleaf.controller;

import com.baizhi.ems_thymeleaf.pojo.User;
import com.baizhi.ems_thymeleaf.service.UserService;
import com.baizhi.ems_thymeleaf.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    //生成驗證碼圖片響應給前端頁面
    @RequestMapping("/generateCode")
    public void generateCode(HttpSession session, HttpServletResponse response) throws IOException {
        //1.生成四位數的驗證碼
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2.將驗證碼保存到session
        session.setAttribute("code",code);
        //3.將驗證碼生成圖片
        response.setContentType("image/png");
        ServletOutputStream output = response.getOutputStream();
        VerifyCodeUtils.outputImage(200,60,output,code);

    }

    //註冊
    @RequestMapping("/register")
    public String register(User user,String code,HttpSession session){
        System.out.println(user);
        System.out.println(code);
        String sessioncode = session.getAttribute("code").toString();
        try{
            if (code != null){
                if (!sessioncode.equals(code)){
                    throw new RuntimeException("驗證碼錯誤");
                }
                userService.regist(user);
                return "redirect:/login";
            }
        }catch (RuntimeException e){
            return "redirect:/regist";
        }
        return "";
    }

    @RequestMapping("/login")
    public String login(User user,HttpSession session){
        try{
            User user1= userService.login(user);
            session.setAttribute("user",user1);
            return "redirect:/emp/list";
        }catch (RuntimeException e){
            return "redirect:/login";
        }
    }
}
